<template>
  <div
    ref="editor"
    class="exercise-editor"
  >
    <h2 class="mb-4 text-2xl font-bold">
      {{ exercise.exercise.exerciseName }}
    </h2>
    <p class="mb-2 text-muted">
      总分：{{ exercise.exercise.exerciseScore }}分 | 题目数量：{{ exercise.questions.length }}道
    </p>

    <div class="mb-6">
      <p class="text-gray-600">
        <span v-if="exercise.studentExercise.state === 'marked'">
          上次得分：{{ exercise.studentExercise.studentScore }}分 ({{ calculateScorePercentage() }}%)
        </span>
        <span v-else>状态：已提交，等待教师批改</span>
      </p>
    </div>

    <div class="space-y-6">
      <div
        v-for="(qwa, index) in exercise.questions"
        :key="qwa.question.questionId"
      >
        <div class="border-l-4 border-blue-500 pl-4 py-2">
          <h4 class="font-semibold text-lg">
            题目 {{ index + 1 }}: 
            <span v-html="getQuestionContentWithoutOptions(qwa.question.questionContent)" />
            <span class="ml-2 text-sm text-gray-500">({{ qwa.question.questionScore }}分)</span>
          </h4>

          <!-- 选择题（支持多选） -->
          <div
            v-if="!qwa.question.type"
            class="mt-3"
          >
            <div
              v-if="exercise.studentExercise.state === 'marked'"
              class="mb-2 text-gray-600"
            >
              <strong>正确答案：</strong> {{ formatOptions(qwa.question.questionAnswer) }}
            </div>
            <div>
              <strong>你的答案：</strong>
              <div class="space-y-1">
                <label 
                  v-for="option in parseOptions(qwa.question.questionContent)" 
                  :key="option.key" 
                  class="flex items-center cursor-pointer"
                >
                  <input 
                    :id="'edit-q-' + index + '-' + option.key" 
                    type="checkbox" 
                    :name="'question-' + index" 
                    :value="option.key"  
                    :disabled="!canEdit || exercise.studentExercise.state === 'marked'"  
                    :checked="getCheckedState(qwa, option.key)" 
                    @change="handleOptionChange($event, index, option.key, qwa)"  
                  >
                  <span class="ml-2 text-gray-700">
                    {{ option.key }}. {{ option.text }}
                  </span>
                </label>
              </div>
            </div>
          </div>

          <!-- 解答题 -->
          <div
            v-else
            class="mt-3"
          >
            <div
              v-if="exercise.studentExercise.state === 'marked'"
              class="mb-2 text-gray-600"
            >
              <strong>参考答案：</strong> {{ qwa.question.questionAnswer || '无参考答案' }}
            </div>
            <div>
              <strong>你的答案：</strong>
              <textarea 
                v-model="qwa.studentAnswer.studentAnswer" 
                class="w-full p-2 border border-gray-300 rounded" 
                rows="3"
                :disabled="!canEdit || exercise.studentExercise.state === 'marked'" 
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="mt-8 text-right">
      <button
        v-if="canEdit && exercise.studentExercise.state === 'submitted'"
        class="btn btn-primary mr-3"
        @click="submitExercise"
      >
        <i class="fa fa-check mr-1" /> 重新提交
      </button>
      <button
        class="btn btn-secondary"
        @click="$emit('back')"
      >
        <i class="fa fa-chevron-left me-1" /> 返回
      </button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  props: {
    exercise: { type: Object, required: true }
  },
  data() {
    return {
      canEdit: false,
      submitting: false
    };
  },
  computed: {
    canSubmit() {
      return this.exercise.questions.some(qwa => 
        !qwa.question.type ? qwa.studentAnswer.studentAnswer.length > 0 : qwa.studentAnswer.studentAnswer.trim() !== ''
      );
    }
  },
  mounted() {
    // 在组件挂载后绑定事件到根元素
    this.editor = this.$refs.editor;
    this.editor.addEventListener('copy', this.handleCopy);
    this.editor.addEventListener('paste', this.handlePaste);
  },
  beforeUnmount() {
    // 组件卸载时移除事件监听器（避免内存泄漏）
    if (this.editor) {
      this.editor.removeEventListener('copy', this.handleCopy);
      this.editor.removeEventListener('paste', this.handlePaste);
    }
  },

  created() {
    // 新增：打印整个exercise数据结构
    console.log('ExerciseEditor初始化时的exercise数据：', this.exercise);

    this.exercise.questions.forEach((qwa, index) => {
      // 新增：打印每个题目项的原始数据
      console.log(`初始化处理题目索引${index}，qwa原始数据：`, qwa);
      
      // 新增：检查studentAnswer是否存在
      if (!qwa.studentAnswer) {
        console.error(`初始化时发现题目索引${index}的studentAnswer为null！`, qwa);
        // 新增：为null时手动初始化，避免后续逻辑崩溃
        qwa.studentAnswer = { studentAnswer: '' };
      }

      if (!qwa.question.type) {
        const raw = qwa.studentAnswer.studentAnswer;
        qwa.studentAnswer.studentAnswer = (() => {
          if (typeof raw === 'string') return raw;
          if (Array.isArray(raw)) return raw.join('');
          return '';
        })()
          .replace(/[^A-Za-z]/g, '')
          .toUpperCase();
      } else {
        qwa.studentAnswer.studentAnswer = qwa.studentAnswer.studentAnswer || '';
      }

      // 新增：打印处理后的studentAnswer值
      console.log(`题目索引${index}处理后的studentAnswer：`, qwa.studentAnswer.studentAnswer);
    });

    this.canEdit = 
      this.exercise.studentExercise.state === 'submitted' && 
      this.exercise.exercise.isMultipleSubmission;

    // 新增：打印最终canEdit状态
    console.log('初始化完成，canEdit状态：', this.canEdit);
  },
  methods: {
    handleCopy(e) {
      // 阻止复制行为（可添加自定义提示）
      e.preventDefault();
      alert('禁止复制'); // 可选提示
    },
    handlePaste(e) {
      // 阻止粘贴行为（可添加自定义提示）
      e.preventDefault();
      alert('禁止粘贴'); // 可选提示
    },
    getQuestionContentWithoutOptions(content) {
      const safeContent = typeof content === 'string' ? content : '';
      const splitResult = safeContent.split(/\n[A-Za-z]\./);
      return splitResult[0] + '<br>';
    },

    parseOptions(content) {
      const options = [];
      const safeContent = typeof content === 'string' ? content : '';
      const regex = /\n\s*([A-Za-z])\.\s*(.+?)(?=\n|$)/g; 
      let match;
      while ((match = regex.exec(safeContent)) !== null) {
        const key = match[1] ? match[1].toUpperCase() : '';
        if (key) {
          options.push({
            key,
            text: match[2] ? match[2].trim() : ''
          });
        }
      }
      return options;
    },

    handleOptionChange(event, index, optionKey, qwa) {
      // 新增：打印当前处理的题目索引和qwa信息
      console.log(`处理选择题变更，题目索引：${index}，optionKey：${optionKey}，qwa内容：`, qwa);
      
      // 新增：检查studentAnswer是否存在
      if (!qwa.studentAnswer) {
        console.error(`题目索引${index}的studentAnswer对象为null！`, qwa);
        return;
      }

      const isChecked = event.target.checked;
      if (typeof optionKey !== 'string' || !optionKey.trim()) {
        console.warn('无效的选项键:', optionKey);
        return;
      }
      const validOption = optionKey.toUpperCase();

      const currentAnswer = (qwa.studentAnswer.studentAnswer || '').toUpperCase();
      
      let newAnswer;
      if (isChecked) {
        newAnswer = [...new Set([...currentAnswer, validOption])].sort().join('');
      } else {
        newAnswer = currentAnswer.replace(new RegExp(validOption, 'g'), '');
      }

      qwa.studentAnswer.studentAnswer = newAnswer;
    },

    getCheckedState(qwa, optionKey) {
      // 新增：打印当前检查的题目和选项
      console.log(`检查选项选中状态，optionKey：${optionKey}，qwa内容：`, qwa);
      
      // 新增：检查studentAnswer是否存在
      if (!qwa.studentAnswer) {
        console.error(`getCheckedState中题目studentAnswer为null！`, qwa);
        return false;
      }

      const answer = (qwa.studentAnswer.studentAnswer || '').toUpperCase();
      return answer.includes(optionKey.toUpperCase());
    },

    async submitExercise() {
      if (this.submitting || !this.canEdit) return;
      this.submitting = true;

      try {
        const userId = this.exercise.studentExercise.id.userId;
        if (!userId) throw new Error("用户ID缺失");

        const submission = {
          studentExercise: {
            id: {
              userId,
              exerciseId: this.exercise.exercise.exerciseId
            },
            state: 'submitted'
          },
          studentQuestionAnswers: this.exercise.questions.map((qwa, index) => {
            // 新增：检查map过程中studentAnswer是否存在
            if (!qwa.studentAnswer) {
              console.error(`提交时发现题目索引${index}的studentAnswer为null！`, qwa);
            }
            return {
              id: {
                userId,
                questionId: qwa.question.questionId,
                exerciseId: this.exercise.exercise.exerciseId
              },
              studentAnswer: qwa.studentAnswer.studentAnswer || '',
              gainScore: 0
            };
          })
        };

        await axios.post('/api/exercises/submitted', submission);
        alert('提交成功！等待教师重新批改');
        this.$emit('refresh-list');
        this.cancelEdit();
      } catch (error) {
        console.error('提交失败:', error.response?.data || error.message);
        alert('提交失败，请检查网络或联系管理员');
      } finally {
        this.submitting = false;
      }
    },

    cancelEdit() {
      this.$emit('back');
      this.canEdit = false;
    },
    calculateScorePercentage() {
      return this.exercise.exercise.exerciseScore > 0 
        ? Math.round((this.exercise.studentExercise.studentScore / this.exercise.exerciseScore) * 100) 
        : 0;
    },
    formatOptions(answer) {
      return answer ? answer.split('').map(letter => `${letter}. `).join('') : '';
    },
    parseLineBreaks(text) {
      return text.replace(/\n/g, '<br>');
    }
  }
};
</script>

<style scoped>
.exercise-editor {
  padding: 2rem;
  margin-top: 2rem;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
</style>
